package com.bss.utils;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private DataSource dataSource;

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.jdbcAuthentication().dataSource(this.dataSource);
		JdbcDaoImpl j = new JdbcDaoImpl();
		j.setDataSource(this.dataSource);
		auth.userDetailsService(j);
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/bss/**").and().ignoring().antMatchers("/images/**").and().ignoring().antMatchers("/styles/**")
				.and().ignoring().antMatchers("/scripts/**").and().ignoring().antMatchers("/a4j/**");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/pages/**").access("hasRole('USER')").and().formLogin()
				.successHandler(new BSSAuthenticationSuccessHandler()).loginPage("/pages/login.jsf")
				.defaultSuccessUrl("/pages/admission.jsf").permitAll().and().csrf().disable();

		// Disabling CSRF as I do not yet know how to put the CSRF token on ajax
		// request and hence it needs fixing
	}
}
